package cn.edu.ljl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

// 对上传文件进行展示，展示所有的文件信息
//未能成功完成。未加入连接

public class listFile extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //req.getRequestDispatcher("./test.jsp").forward(req,resp);
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sql="SELECT * FROM files ORDER BY id DESC";
        request.setCharacterEncoding("UTF-8");

        try {
            List<file> files=DBMS.getFiles(sql);
            response.setCharacterEncoding("UTF-8");
            Writer writer = response.getWriter();
            StringBuilder sb =new StringBuilder();

            sb.append(Page.getHeader());
            sb.append(toHtml(files));
            sb.append(Page.getEnd());
            writer.write(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private String toHtml (List<file> files){
        StringBuilder sb =new StringBuilder();
        sb.append("<center><br><table style='width:65%' border='0' cellpadding='10'>");

        sb.append("<tr style='background-color:#336699;color:#ff5400'>" +
                "<th>编号</th><th>名字</th><th>文件</th>" +
                "<th></th><th></th></tr>");
        for (int i=0; i<files.size(); i++) {
            file file =files.get(i);
            if (i % 2 == 0) {
                sb.append("<tr style='background-color:#20b2aa'>");
            } else {
                sb.append("<tr style='background-color:#7ab8cc'>");
            }
            sb.append("<td>").append(file.getID()).append("</td>");
            sb.append("<td><b>").append(file.getName()).append("</b></td>");

//            <iframe src='https://view.officeapps.live.com/op/view.aspx?src=http://storage.xuetangx.com/public_assets/xuetangx/PDF/1.xls' width='100%' height='100%' frameborder='1'>
//</iframe>

            sb.append("<td><msword  src='/gittest/uploadFile/").append(file.getFile()).append("'></msword></td>");

//
//            sb.append("<td>").append(
//                    String.format("<a href='./update?id=%s'>修改</a>", student.getID())
//            ).append("</td>");
//            sb.append("<td>").append(
//                    String.format("<a href='./delete?id=%s'>删除</a>", student.getID())
//            ).append("</td>");
//            sb.append("</tr>");
        }
        sb.append("</table></center>");
        return sb.toString();

    }
}
